<?php

namespace app\admin\controller\procurement;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;

use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\exception\FileException;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="rule")
 */
class Rule extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Rule();

    }

    public function test()
    {

        $config = [
            'path' => getTmpDir() // xlsx文件保存路径
        ];

        $excel = new \Vtiful\Kernel\Excel($config);
        $arr = get_class_methods($excel);
        dd($arr);
//        $num = bcdiv((0.2-0.05),0.05,2);
//
//
//        $str = '0.2';
//        $float = floatval($str);
//        $num = bcdiv(($float-0.05),0.05,2);
//
//        dd(ceil($num));
//        set_time_limit(0);

        $arr = [
                ['name' => 'taylor', 'framework' => 'laravel','age'=>18],
                ['name' => 'ze', 'framework' => 'laravel','age'=>18],
                ['name' => 'chn', 'framework' => 'laravel','age'=>18],
            ];

        $collect = collection($arr);
        $keys = $collect->whereIn('name', ['ze'])->keys()->flatten()->toArray();

        $res = $collect->forget($keys);
        sleep(60);
        dd($res);



    }

    /**
     * @NodeAnotation(title="模板下载",auth=false)
     */
    public function template()
    {

        $header = ['规则名称'];

        $title = '规则管理导入模板';

        exportExcel($title,$header);

        //return Excel::exportData([], $header, $fileName, 'xlsx');
    }


    /**
     * @NodeAnotation(title="导入")
     */
    public function import()
    {


        $row = $this->request->get();
        if ($this->request->isAjax()) {

//            获取上传文件x
            $file = $this->request->file('file');

//            $savename = \think\facade\Filesystem::putFile( 'topic', $file);
//
//
////            dd(runtime_path(), $savename);
//            $res = unlink('D:\phpstudy_pro\WWW\jit_gitlib\runtime/storage/'. $savename);
//
//            dd($res);


//           读取上传文档 从第二行开始
            $data = Excel::import($file, 2);

//            构建插入数据
            $time = time();
            $collect = collection($data)->map(function ($item) use ($time) {
                return ['name' => $item[0], 'create_time' => $time, 'update_time' => $time];
            })->toArray();
//            dd($collect);

//          可以分段插入设置$limit  insertAll($date,$limit)
            $insertAll = $this->model->insertAll($collect);

            $insertAll ? $this->success('导入成功') : $this->error('导入失败');

        }

        $this->assign('row', $row);
        return $this->fetch();
    }


}